package cn.com.cfae.iras.doc.analyze.components.consistency;

import cn.com.cfae.iras.doc.analyze.components.BaseComponent;
import cn.com.cfae.iras.doc.analyze.components.beans.ComponentResult;
import cn.com.cfae.iras.doc.analyze.components.commonsense.C1002;
import cn.com.cfae.iras.doc.analyze.parse.kv.KVText;
import cn.com.cfae.iras.doc.analyze.parse.kv.TextLayout;
import cn.com.cfae.iras.doc.analyze.parse.model.ChapterModel;
import cn.com.cfae.iras.doc.analyze.parse.model.DocumentModel;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.annotation.AccessType;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by zouxun on 2018/10/29
 */
@Component("U1008")
@Scope("prototype")
public class U1008 extends BaseComponent {
    private static Logger logger = LoggerFactory.getLogger(U1008.class);

    @Autowired
    U1004 u1004;
    @Autowired
    C1002 c1002;

    /**
     * @desc 抓取募集说明书中首页和M-3-1“注册发行总额”，例如“人民币壹拾伍亿元（RMB1,500,000,000 元）”；判断是否大写与数字格式是否一致；
     * 1、检查首页、M-3章节中的注册发行总额是否一致；
     * 2、分别从首页、M-3章节抽取注册发行注册总额；
     * 3、不一致提示；
     * @return
     */
    @Override
    public List<ComponentResult> handlerM() {
        logger.info("开始调用U1008组件，处理M表...............");
        String m0CatalogId="M-0";
        String m0ChapterId="M-0-1";
        List<ComponentResult> componentResults = ruleCheck(m0CatalogId,m0ChapterId);
        return componentResults;
    }

    @Override
    public List<ComponentResult> handlerBM() {
        logger.info("开始调用U1008组件，处理BM表...............");
        String m0CatalogId="BM-0";
        String m0ChapterId="BM-0-1";
        List<ComponentResult> componentResults = ruleCheck(m0CatalogId,m0ChapterId);
        return componentResults;
    }

    @Override
    public List<ComponentResult> handlerDM() {
        logger.info("开始调用U1008组件，处理DM表...............");
        String m0CatalogId="DM-0";
        String m0ChapterId="DM-0-1";
        List<ComponentResult> componentResults = ruleCheck(m0CatalogId,m0ChapterId);
        return componentResults;
    }

    @Override
    public List<ComponentResult> handlerBDM() {
        logger.info("开始调用U1008组件，处理BDM表...............");
        String m0CatalogId="BDM-0";
        String m0ChapterId="BDM-0-1";
        List<ComponentResult> componentResults = ruleCheck(m0CatalogId,m0ChapterId);
        return componentResults;
    }


    private List<ComponentResult> ruleCheck(String m0CatalogId,String m0ChapterId){
        DocumentModel documentModel = super.getExtractData();

        ChapterModel m3ChapterModel = documentModel.getChapterModel(getCatalogId());

        ChapterModel m0ChapterModel = documentModel.getChapterModel(m0CatalogId);

        List<ComponentResult> componentResults = new ArrayList<>();

        ComponentResult m0ComponentResult = u1004.getComponentResult(getCatalogId(),m0ChapterId,getRuleTitle(),"检查首页、发行条款中的注册发行总额是否一致","",true,getRegulationId(),1,null,"03");
        ComponentResult m3ComponentResult = u1004.getComponentResult(getCatalogId(),getChapterId(),getRuleTitle(),"检查首页、发行条款中的注册发行总额是否一致","",true,getRegulationId(),3,null,"03");

        try{
            boolean m0Flag = true;
            boolean m3Flag = true;

            String m0Text = null;
            String m3Text = null;

            Map<String,String> originalValueMap = new HashMap<>();

            if(m3ChapterModel!=null){
                m3ComponentResult.setPageNum(m3ChapterModel.getStartPage());

                //M-3注册发行总额
                KVText m3KVTextValue = getKVTextValue(getCatalogId(),"FXTK","ZCZJE");
                KVText m3KVTextKey = getKVTextKey(getCatalogId(),"FXTK","ZCZJE");

                if(m3KVTextValue!=null){
                    m3Text=m3KVTextValue.getText();
                    logger.info("M-3注册发行总额：{}",m3Text);

                    List<ComponentResult.TextPosition> contentAndPositionList = new ArrayList();
                    if(m3KVTextKey!=null){
                        TextLayout textLayout = m3KVTextKey.getTextLayout();
                        ComponentResult.TextPosition textPosition = new ComponentResult().new TextPosition();
                        if(textLayout!=null){
                            textPosition.setContent(textLayout.getText());
                            textPosition.setX(textLayout.getLeft());
                            textPosition.setY(textLayout.getTop());
                            contentAndPositionList.add(textPosition);
                        }
                        m3ComponentResult.setPageNum(m3KVTextKey.getPageNumber());
                    }
                    m3ComponentResult.setTextPosition(contentAndPositionList);

                    if(StringUtils.isNotEmpty(m3Text)){
                        originalValueMap.put("m3Text",m3Text);

                        m3Text = dealAmount(m3Text);
                        if(StringUtils.isNotEmpty(m3Text)){
                            logger.info("第三章发行条款注册发行总额,数据格式处理：{}",m3Text);
                            m3ComponentResult.setPromptMessage("已识别".concat(getChapterId()).concat("注册发行总额：").concat(originalValueMap.get("m3Text")));
//                            m3ComponentResult.setAnnotationFlag(false);
                        }else{
                            m3ComponentResult.setPromptMessage("未识别".concat(getChapterId()).concat("注册发行总额，建议人工核对"));
                            m3Flag=false;
                        }
                    }else{
                        m3ComponentResult.setPromptMessage("未识别".concat(getChapterId()).concat("注册发行总额，建议人工核对"));
                        m3Flag=false;
                    }
                }else{
                    m3Flag=false;
                    m3ComponentResult.setPromptMessage("未识别".concat(getChapterId()).concat("注册发行总额，建议人工核对"));
                }

            }else{
                m3ComponentResult.setPromptMessage("未识别".concat(getCatalogId()).concat("数据，建议人工核对"));
                m3Flag=false;
            }

            if(m0ChapterModel!=null){
                m0ComponentResult.setPageNum(m0ChapterModel.getStartPage());

                //M-0注册发行总额
                KVText m0KVTextValue = getKVTextValue(m0CatalogId,"FXTK","ZCZJE");
                KVText m0KVTextKey= getKVTextKey(m0CatalogId,"FXTK","ZCZJE");

                if(m0KVTextValue!=null){
                    m0Text = m0KVTextValue.getText();
                    logger.info("首页注册发行总额：{}",m0Text);

                    List<ComponentResult.TextPosition> contentAndPositionList = new ArrayList();
                    if(m0KVTextKey!=null){
                        TextLayout textLayout = m0KVTextKey.getTextLayout();
                        if(textLayout!=null){
                            ComponentResult.TextPosition textPosition = new ComponentResult().new TextPosition();
                            textPosition.setContent(textLayout.getText());
                            textPosition.setX(textLayout.getLeft());
                            textPosition.setY(textLayout.getTop());
                            contentAndPositionList.add(textPosition);
                        }
                    }
                    m0ComponentResult.setTextPosition(contentAndPositionList);

                    if(StringUtils.isNotEmpty(m0Text)){
                        originalValueMap.put("m0Text",m0Text);

                        m0Text = dealAmount(m0Text);
                        if(StringUtils.isNotEmpty(m0Text)){
                            logger.info("首页注册发行总额，数据格式处理：{}",m0Text);
                            m0ComponentResult.setPromptMessage("已识别首页注册发行总额：".concat(originalValueMap.get("m0Text")));
//                            m0ComponentResult.setAnnotationFlag(false);
                        }else{
                            m0ComponentResult.setPromptMessage("未识别首页注册发行总额，建议人工核对");
                            m0Flag=false;
                        }
                    }else{
                        m0ComponentResult.setPromptMessage("未识别首页注册发行总额，建议人工核对");
                        m0Flag=false;
                    }
                }else{
                    m0ComponentResult.setPromptMessage("未识别首页注册发行总额，建议人工核对");
                    m0Flag=false;
                }

            }else{
                m0ComponentResult.setPromptMessage("未识别首页数据，建议人工核对");
                m0Flag=false;
            }

            if(!m0Flag || !m3Flag){
                m0ComponentResult.setExist("03");
                m3ComponentResult.setExist("03");

                m0ComponentResult.setAnnotationFlag(true);
                m3ComponentResult.setAnnotationFlag(true);
            }

            if(m0Flag && m3Flag){
                if(Double.parseDouble(m0Text)==Double.parseDouble(m3Text)){
                    logger.info("对比一致");
                    m0ComponentResult.setPromptMessage("对比一致，".concat("首页注册发行总额：").concat(originalValueMap.get("m0Text")));
                    m3ComponentResult.setPromptMessage("对比一致，".concat(getChapterId()).concat("注册发行总额：").concat(originalValueMap.get("m3Text")));

                    m0ComponentResult.setAnnotationFlag(false);
                    m3ComponentResult.setAnnotationFlag(false);

                    m0ComponentResult.setExist("01");
                    m3ComponentResult.setExist("01");
                }else{
                    logger.info("对比不一致");
                    m0ComponentResult.setPromptMessage("对比不一致，".concat("首页注册发行总额：").concat(originalValueMap.get("m0Text")));
                    m3ComponentResult.setPromptMessage("对比不一致，".concat(getChapterId()).concat("注册发行总额：").concat(originalValueMap.get("m3Text")));

                    m0ComponentResult.setAnnotationFlag(true);
                    m3ComponentResult.setAnnotationFlag(true);

                    m0ComponentResult.setExist("02");
                    m3ComponentResult.setExist("02");
                }
            }
        }catch (Exception e){
            logger.error(e.getMessage(),e);
        }

        componentResults.add(m0ComponentResult);
        componentResults.add(m3ComponentResult);

        return componentResults;
    }

    private String dealAmount(String text){
        Map<String,String> capitalAmountMap = new HashMap<>();
        capitalAmountMap.put("壹","1");
        capitalAmountMap.put("贰","2");
        capitalAmountMap.put("叁","3");
        capitalAmountMap.put("肆","4");
        capitalAmountMap.put("伍","5");
        capitalAmountMap.put("陆","6");
        capitalAmountMap.put("柒","7");
        capitalAmountMap.put("捌","8");
        capitalAmountMap.put("玖","9");
        capitalAmountMap.put("拾","10");
        capitalAmountMap.put("佰","100");

        String result = null;

        try{
            text = text.replaceAll("[,|，|\\s]{1,}","");
            logger.info("格式处理：{}",text);

            String amountRegex = ".*亿.*";
            Pattern pattern = Pattern.compile(amountRegex);
            Matcher matcher = pattern.matcher(text);

            if(matcher.matches()){
                String numberRegex = ".*\\d+亿.*";
                pattern = Pattern.compile(numberRegex);
                matcher = pattern.matcher(text);

                if (matcher.matches()) {
                    String regex = "(\\d{0,}\\.{0,1}\\d{1,}亿){1}";
                    pattern = Pattern.compile(regex);
                    matcher = pattern.matcher(text);
                    if (matcher.find()) {
                        logger.info("匹配结果：{}",matcher.group());

                        result = matcher.group();

                        result = result.substring(0,result.indexOf("亿"));
                    }
                    return result;
                }else{
                    String capitalRegex = "[零|壹|贰|叁|肆|伍|陆|柒|捌|玖|拾|佰]{1,}亿";
                    pattern = Pattern.compile(capitalRegex);
                    matcher = pattern.matcher(text);

                    if(matcher.find()){
                        logger.info("匹配结果：{}",matcher.group());

                        String capitalAmountText = matcher.group();

                        if(capitalAmountText.contains("佰") && capitalAmountText.contains("拾")){
                            //百位数
                            String hundredDigit = capitalAmountText.substring(0,capitalAmountText.indexOf("佰"));
                            logger.info("百位数：{}",hundredDigit);
                            //十位数
                            String tenDigit = capitalAmountText.substring(capitalAmountText.indexOf("佰")+1,capitalAmountText.indexOf("拾"));
                            logger.info("十位数：{}",tenDigit);
                            //个位数
                            String singleDigit = capitalAmountText.substring(capitalAmountText.indexOf("拾")+1,capitalAmountText.indexOf("亿"));

                            BigDecimal hundredDecimal = new BigDecimal(capitalAmountMap.get(hundredDigit));
                            BigDecimal tenDecimal = new BigDecimal(capitalAmountMap.get(tenDigit));

                            BigDecimal tempCount = hundredDecimal.multiply(BigDecimal.valueOf(100)).add((tenDecimal.multiply(BigDecimal.TEN)));
                            logger.info("tempCount：{}",tempCount.stripTrailingZeros().toPlainString());

                            if(StringUtils.isNotEmpty(singleDigit)){
                                logger.info("个位数：{}",singleDigit);

                                BigDecimal singleDecimal = new BigDecimal(capitalAmountMap.get(singleDigit));

                                result = tempCount.add(singleDecimal).stripTrailingZeros().toPlainString();
                            }else{
                                result = tempCount.stripTrailingZeros().toPlainString();
                            }

                            logger.info("得出结果：{}",result);

                        }else if(capitalAmountText.contains("佰") && !capitalAmountText.contains("拾")){
                            //百位数
                            String hundredDigit = capitalAmountText.substring(0,capitalAmountText.indexOf("佰"));
                            logger.info("百位数：{}",hundredDigit);
                            //个位数
                            String singleDigit = capitalAmountText.substring(capitalAmountText.indexOf("佰")+1,capitalAmountText.indexOf("亿"));

                            BigDecimal hundredDecimal = new BigDecimal(capitalAmountMap.get(hundredDigit));

                            if(StringUtils.isNotEmpty(singleDigit)){
                                logger.info("个位数：{}",singleDigit);

                                singleDigit = singleDigit.substring(1);

                                BigDecimal singleDecimal = new BigDecimal(capitalAmountMap.get(singleDigit));

                                result = hundredDecimal.multiply(BigDecimal.valueOf(100)).add(singleDecimal).stripTrailingZeros().toPlainString();
                            }else{
                                result = hundredDecimal.multiply(BigDecimal.valueOf(100)).stripTrailingZeros().toPlainString();
                            }

                            logger.info("得出结果：{}",result);
                        }else if(!capitalAmountText.contains("佰") && capitalAmountText.contains("拾")){
                            //十位数
                            String tenDigit = capitalAmountText.substring(0,capitalAmountText.indexOf("拾"));
                            logger.info("十位数：{}",tenDigit);
                            //个位数
                            String singleDigit = capitalAmountText.substring(capitalAmountText.indexOf("拾")+1,capitalAmountText.indexOf("亿"));

                            BigDecimal tenDecimal = new BigDecimal(capitalAmountMap.get(tenDigit));

                            if(StringUtils.isNotEmpty(singleDigit)){
                                logger.info("个位数：{}",singleDigit);

                                BigDecimal singleDecimal = new BigDecimal(capitalAmountMap.get(singleDigit));

                                result = tenDecimal.multiply(BigDecimal.TEN).add(singleDecimal).stripTrailingZeros().toPlainString();
                            }else{
                                result = tenDecimal.multiply(BigDecimal.TEN).stripTrailingZeros().toPlainString();
                            }

                            logger.info("得出结果：{}",result);
                        }else{
                            //个位数
                            String singleDigit = capitalAmountText.substring(0,capitalAmountText.indexOf("亿"));
                            logger.info("个位数：{}",singleDigit);
                            result = capitalAmountMap.get(singleDigit);

                            logger.info("得出结果：{}",result);
                        }

                    }
                }
            }else{
                amountRegex = ".*元.*";
                pattern = Pattern.compile(amountRegex);
                matcher = pattern.matcher(text);

                if(matcher.matches()){
                    String regex = "\\d{1,}";
                    pattern = Pattern.compile(regex);
                    matcher = pattern.matcher(text);

                    String num = null;

                    if(matcher.find()){
                        num = matcher.group(0);
                    }

                    if(StringUtils.isNotEmpty(num)){
                        matcher = pattern.matcher(num);
                        if(matcher.matches()){
                            BigDecimal bigDecimal = new BigDecimal(num);
                            BigDecimal numDecimal = bigDecimal.divide(BigDecimal.valueOf(100000000));
                            return numDecimal.stripTrailingZeros().toPlainString();
                        }
                    }
                }
            }
        }catch (Exception e){
            logger.error(e.getMessage(),e);
        }

        return result;
    }

}
